<?php
ini_set('display_errors',1);            //错误信息
ini_set('display_startup_errors',1);    //php启动错误信息
error_reporting(-1);                    //打印出所有的 错误信息

class WxInlet {
    protected $server_url = 'http://101.132.71.127:8088';
    protected $app_id = 'wxd4f4350d72afdd1c';
    protected $app_secret = '4cb132ef1a924759b9f742530696ed96';
    protected $wap_url = '';

    public function __construct() {
        $http = $_SERVER['SERVER_PROTOCOL'] == 'HTTP/1.0' ? 'http://' : 'https://';
        $arr = explode(':', $_SERVER['HTTP_HOST']);
        $this->wap_url = $http . $arr[0];
    }

    /*
     * 向微信获取授权code
     */
    public function inlet() {
        header("Content-type: text/html; charset=utf-8");

        if (! $this->is_wechat()) {
            die('请使用微信打开！');
        }

        $type = $_GET['type'] ? $_GET['type'] : 1;
        $url = $_GET['url'] ? $_GET['url'] : '';

        $redirect_uri = urlencode($this->wap_url . '/WxInlet.php?mode=callback&type=' . $type . ($url ? '&url=' . $url : ''));
        $url = "https://open.weixin.qq.com/connect/oauth2/authorize?appid={$this->app_id}&redirect_uri={$redirect_uri}&response_type=code" .
            "&scope=snsapi_userinfo&state=1#wechat_redirect";

        header('location:'.$url);
    }

    /*
     * 微信回调传回code
     */
    public function callback() {
        header("Content-type: text/html; charset=utf-8");

        $code = $_GET['code'];
        $type = isset($_GET['type']) ? $_GET['type'] : 1;
        $callback_url = isset($_GET['url']) ? $_GET['url'] : '';

        if (empty($code)) die('授权失败！');

        $token_url = "https://api.weixin.qq.com/sns/oauth2/access_token?appid={$this->app_id}&secret={$this->app_secret}".
            "&code={$code}&grant_type=authorization_code";
        $token = json_decode(file_get_contents($token_url));
        if (isset($token->errcode)) {
            die($token->errmsg);
        }

        $url = $this->server_url . '/mobile/api/v1/Login.php?mode=wx_login';
        $data = array(
            'openid' => $token->openid,
            'access_token' => $token->access_token
        );
        $arr = $this->curl_post($url, $data);

        if ($arr['code'] == 200) {
            $user = $arr['data'];
        } else {
            $user_info_url = "https://api.weixin.qq.com/sns/userinfo?access_token={$token->access_token}&openid=".
                "$token->openid&lang=zh_CN";
            $user_info = json_decode(file_get_contents($user_info_url));
            if (isset($user_info->errcode)) {
                die($token->errmsg);
            }

            $url = $this->server_url . '/mobile/api/v1/Login.php?mode=wx_register';
            $data = array(
                'openid' => $token->openid,
                'access_token' => $token->access_token,
                'nickname' => $user_info->nickname,
                'headimg' => $user_info->headimgurl,
                'callback_url' =>$callback_url,
            );
            $arr = $this->curl_post($url, $data);

            if ($arr['code'] != 200) {
                die('服务器异常，请重访问！');
            }

            $user = $arr['data'];
        }

        setcookie('uid', $user['uid']);
        setcookie('time', $user['time']);
        setcookie('token', $user['token']);

        switch ($type) {
            case 1:
                $url = $this->wap_url;
                break;
            case 2:
                $url = $this->wap_url . '/head/share';
                break;
            case 3:
                $url = $this->wap_url . '/center';
                break;
            case 4:
                $url = urldecode($callback_url);
                break;
        }

        header('location:'.$url);
    }

    /*
     * 微信公众号绑定地址
     */
    public function test() {
        /*$echoStr = $_GET["echostr"];
        if($this -> checkSignature()){
            echo $echoStr;
        }*/

        include_once('WxEvent.php');
        $obj = new WxEvent($this->server_url, $this->app_id, $this->app_secret, $GLOBALS['HTTP_RAW_POST_DATA']);
        $obj->index();
    }

    /*
     * 绑定时判断秘钥是否正确
     */
    private function checkSignature(){
        $signature = $_GET["signature"];
        $timestamp = $_GET["timestamp"];
        $nonce = $_GET["nonce"];
        $token = '218233AF796F235E46284D22A2E308D5';
        $tmpArr = array($token, $timestamp, $nonce);
        sort($tmpArr, SORT_STRING);
        $tmpStr = implode($tmpArr);
        $tmpStr = sha1($tmpStr);
        if($tmpStr == $signature){
            return true;
        }else{
            return false;
        }
    }

    protected function curl_post($url, $data) {
        if (strpos($url,'https://')) {
            $rel = $this->curl_https_post($url, $data);
        } else {
            $rel = $this->curl_http_post($url, $data);
        }

        return $rel;
    }

    /*
     * 模拟post请求(http)
     */
    protected function curl_http_post($url, $data) {
        $ch = curl_init();

        curl_setopt($ch, CURLOPT_URL, $url);
        curl_setopt($ch, CURLOPT_RETURNTRANSFER, 1);
        // post数据
        curl_setopt($ch, CURLOPT_POST, 1);
        // post的变量
        curl_setopt($ch, CURLOPT_POSTFIELDS, $data);

        $output = curl_exec($ch);
        curl_close($ch);

        if( preg_match('/^\xEF\xBB\xBF/', $output) ) {
            $output = substr($output,3);
        }
        $output = json_decode(trim($output), true);

        return $output;
    }

    /*
 * 模拟post请求(https)
 */
    function curl_https_post($url, $data) {
        $curl = curl_init(); // 启动一个CURL会话
        curl_setopt($curl, CURLOPT_URL, $url); // 要访问的地址
        curl_setopt($curl, CURLOPT_SSL_VERIFYPEER, 0); // 对认证证书来源的检查
        curl_setopt($curl, CURLOPT_SSL_VERIFYHOST, 1); // 从证书中检查SSL加密算法是否存在
        curl_setopt($curl, CURLOPT_USERAGENT, $_SERVER['HTTP_USER_AGENT']); // 模拟用户使用的浏览器
        curl_setopt($curl, CURLOPT_FOLLOWLOCATION, 1); // 使用自动跳转
        curl_setopt($curl, CURLOPT_AUTOREFERER, 1); // 自动设置Referer
        curl_setopt($curl, CURLOPT_POST, 1); // 发送一个常规的Post请求
        curl_setopt($curl, CURLOPT_POSTFIELDS, $data); // Post提交的数据包
        curl_setopt($curl, CURLOPT_TIMEOUT, 30); // 设置超时限制防止死循环
        curl_setopt($curl, CURLOPT_HEADER, 0); // 显示返回的Header区域内容
        curl_setopt($curl, CURLOPT_RETURNTRANSFER, 1); // 获取的信息以文件流的形式返回
        $output = curl_exec($curl); // 执行操作
        /*if (curl_errno($curl)) {
            echo 'Errno'.curl_error($curl);//捕抓异常
        }*/
        curl_close($curl); // 关闭CURL会话

        if( preg_match('/^\xEF\xBB\xBF/', $output) ) {
            $output = substr($output,3);
        }
        $output = json_decode(trim($output), true);

        return $output;
    }

    /*
     * 判断是否是微信浏览器
     */
    protected function is_wechat() {
        if (strpos($_SERVER['HTTP_USER_AGENT'], 'MicroMessenger') !== false) {
            return true;
        }

        return false;
    }

    public function wxCallback() {
        header("Content-type: text/html; charset=utf-8");
        include_once('WxCallback.php');
        $obj = new WxCallback();
        $type = $_GET['type'];

        switch ($type) {
            case 1:
                $appid = $_GET['appid'];
                $appsecret = $_GET['appsecret'];
                $obj->getAccessToken($appid, $appsecret);
                break;
            case 2:
                $access_token = $_POST['access_token'];
                $menu = $_POST['menu'];
                $obj->setMenu($access_token, $menu);
                break;
            case 3:
                $access_token = $_GET['access_token'];
                $file = urldecode($_GET['file']);
                $type = $_GET['img_type'];
                $obj->uploadTmp($access_token, $file, $type);
                break;
        }
    }
}

$obj = new WxInlet();
$obj->$_GET['mode']();

